/***************************************************************************
 创建者: 华磊
 开始时间: 2018.8.14
 copyright: (C) 华友高科
 修改说明: (每次有修改就添加一条，带有 修改人，修改时间，修改描述)
 example (1) hualei 2017.5.8 类的具体实现代码编写

 版本说明
 V1.11 hualei　2018.10.29 深圳动劲测试用。
 V1.12 hualei  2018.11.2　东莞宏友测试
 V1.13 hualei 2018.11.8　深圳橙子测试用。
 V1.14 hualei 2018.11.10 深圳欧凯测试用。
 V1.15 hualei 2018.11.27 东莞华盛控测试。
 V1.23 hualei 2019.3.29 福德要求修改手动加速度。
 ***************************************************************************/
//线程说明 :查看线程命令　top -H -p (pid)
//1 main thread PR -31 (50对应)
//7 vrep PR -31
//* modbuscom PR -96
//* canbuscom PR -99　(98对应)
//8 globalManager PR 20
//9 safetyWatchDong PR -51
//10 safetyFunction PR -51
//21RosApi threadRun1 PR 20
//22 RosApi threadRun2 PR -31
//23 TrajectoryServer loopcommon PR -41
//25~34 程序引擎ProgramEngine PR -83  (显示名称QThread)
//３5－４１　gsoapServer PR  -31

//42 JoyStickDelegate PR
#define D_MAIN_VERSION "V3.174p"
#define D_PUBLISH_DATE "2022.3.8"

#ifdef D_USE_UI
#include <QApplication>
#include "mainwindow.h"
#include "testform.h"

#else
#include <QCoreApplication>
#endif
#include <QTextCodec>
#include <QSharedMemory>
#include <QDebug>
#include <stdlib.h>
#include "motionform.h"
#include "robotmanager.h"
#include "robotengine.h"
#include "powermanager.h"
#include "domparser.h"
#include "hmigsoapqt.h"
#include "globalmanager.h"
#include "timetool.h"
#include "robotcontrol.h"
#include "echoserver.h"
#include "commrobotiq.h"
#include "ultrasonicsensor.h"
#include "websocketserver.h"
#include "tcpmanager.h"
#include "modbusmanager.h"
#include "fleetservice.h"
#include "socketfleetadapter.h"
#include "messagelog.h"
#include "globalregister.h"
#include "joystickdelegate.h"

#ifdef D_USE_UI
#include "vreptest.h"
#else
#include "vrepobject.h"
#include "vrepcontrol.h"
#endif

PowerManager* p_powerManger=NULL;
RobotControl* robCtl=NULL;//heap kongjian problem?
UltrasonicSensor *g_ultrasonicSensor=NULL;
HmiGsoapQt *commHmi=NULL;
TcpManager *tcpManager = NULL;
ModbusManager *modbusManager = NULL;
FleetService *fleetService=NULL;
QMainWindow *g_mainWindow=NULL;
SocketFleetAdapter *socketFleetAdapter=NULL;
GlobalRegister *g_globalRegister=NULL;
JoyStickDelegate *g_joystickDelegate=NULL;
int main(int argc, char *argv[]){
#ifdef D_USE_UI
    QApplication a(argc, argv);
#else
    QCoreApplication a(argc, argv);
#endif
    qDebug()<<"机器人控制内核，版本"<<D_MAIN_VERSION;

    robCtl=new RobotControl;

    qRegisterMetaType< VehiclePosition > ("VehiclePosition");

    //防止main启动２个实例
//    QSharedMemory sh;
//    sh.setKey(  a.applicationName() );

//    if(  sh.attach() ){
//        qDebug()<<" app is runing! exit 0;";
//        return 0;
//    }

//    if( !sh.create(1) ){
//        qDebug()<<"error: reboot require!  exit -1;";
//        return -1;
//    }

    //设置优先级
    struct sched_param param;
    param.__sched_priority = 30;
    sched_setscheduler(0,SCHED_RR,&param);

     qDebug()<<"************************MainThread pid="<<getpid();
//    int policy, priority;
//    pthread_getschedparam(pthread_self(), &policy, (struct sched_param *)&priority);
//    if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1)
//    {
//        qDebug("main thread mlockall failed");
//    }

    //设置ＱＴ字体
    #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
        QTextCodec *codec = QTextCodec::codecForName( "UTF-8" );
        QTextCodec::setCodecForLocale(codec);
        QTextCodec::setCodecForCStrings(codec);
        QTextCodec::setCodecForTr(codec);
    #else
        QTextCodec *codec = QTextCodec::codecForName( "UTF-8" );
        QTextCodec::setCodecForLocale(codec);
    #endif
    //p_powerManger
     p_powerManger=NULL;

    //初始化TimeTool，MessageLog实例
    TimeTool::getInstance();
    MessageLog::getInstance();

    //初始化EcatMaster
    robCtl->init();
    sleep(2);


    //初始化PowerManager
    //１）实例化
//    PowerManager powerm;
    //２）指针给全局变量
    p_powerManger = new PowerManager;   //HmiGsoapQt用p_powerManger

    //３）注册主程序版本
    ComponentVersion versionInfo;
    versionInfo.componentName="AgvBaseControl";
    versionInfo.componentVersion=D_MAIN_VERSION;
    versionInfo.publishDate=D_PUBLISH_DATE;
    p_powerManger->registerComponentVersion(versionInfo);
    //４）初始化PowerManager机器人
    p_powerManger->initRobots();
    p_powerManger->refreshVersionList();
    bool robotIsInitialed=false;
    if(p_powerManger->getRobotCount()>0)
    {
        robotIsInitialed=true;
    }

    //5)初始化算法轴模式
    robCtl->initialMotorControlMode();


    p_powerManger->startSafetyCheck();
    //初始化HmiGsoapQt
    commHmi=new HmiGsoapQt();
    
    // TcpManager 实例化
    tcpManager = new TcpManager;
    //modbus服务对象
    QString modbusManagerConfigFilePath=D_TCRCONTROLLER_DATA_PATH;
    modbusManagerConfigFilePath+=D_MODBUS_MANAGER_CONFIG_FILE_PATH;
    modbusManager=new ModbusManager(modbusManagerConfigFilePath,p_powerManger);

//    #ifdef D_USE_ROS
    //fleet初始化
    fleetService =new FleetService(p_powerManger);

    QString socketFleetConfigFilePath=D_TCRCONTROLLER_DATA_PATH;
    socketFleetConfigFilePath+=D_SOCKET_FLEET_CONFIG_FILE_PATH;
    socketFleetAdapter=new SocketFleetAdapter(socketFleetConfigFilePath,fleetService);
//    #endif

    #ifdef D_USE_UI
    //主窗口
    MainWindow *mainWindow=new MainWindow(p_powerManger);
    g_mainWindow=mainWindow;
    mainWindow->setMainVersion(versionInfo.componentVersion,versionInfo.publishDate);


    //ＩＯ及电机调试窗口
    testForm* ecatForm;
    ecatForm= new testForm();


    //如果配置文件有问题，此处可能导致coredump
    //算法调试窗口
//     MotionForm *motionForm;
//     if(true==robotIsInitialed)
//     {
//        motionForm = new MotionForm(p_powerManger->robotManager->robotsMap[1]->programEngine
//                ->programMcController->mcControllerInterpreter);
//     }
//     else
//     {
//         motionForm = new MotionForm(NULL);
//     }

    //VREP调试窗口
    VrepTest* vrepForm;
    vrepForm= new VrepTest();
    vrepForm->vrepControl=robCtl->vrepCtl;
    int tmpVrepSimulateionRobot;
    if(1==robCtl->getVrepSimulationRobotId(tmpVrepSimulateionRobot))
    {
        vrepForm->startConnectVrep(tmpVrepSimulateionRobot);
    }

    mainWindow->ecatForm=ecatForm;
//    mainWindow.motionForm=motionForm;
    mainWindow->vrepForm=vrepForm;
    mainWindow->setGeometry(70,0,871,717);
    mainWindow->show();
    //显示
    mainWindow->vrepForm->setGeometry(1500,500,300,500);
//    vrepForm->show();
//    mainWindow.ecatForm->setGeometry(700,30,300,300);
//    ecatForm->show();
//    mainWindow.motionForm->setGeometry(1000,40,500,700);

    mainWindow->showMotionForm();
    #endif

    //webserver初始化
    WebSocketServer *webServer=new WebSocketServer(p_powerManger);



    //webserver初始化
//    std::vector <ComponentVersion> componentVersionList;
//    webobj.readVersion(componentVersionList);
//    p_powerManger->registerComponentVersion(componentVersionList[0]);
//    webobj.start();
//    while( !webobj.isRunning())
//    {
//        usleep(100);
//    }
//    webctl.socketConnect( "", 1234 );
//    qDebug()<<"webserver初始化完成－－－－－－－－－－－－－－－－－－－－－";


//    //roscommunicate接口模块初始化
//    RosCommunicate rosCommunicate;
//    rosCommunicate.createThread();

    //只有调用了一次lv1之后HMI才能每次都正常连接（诡异）
    UserInfo userInfo;//ENUM_POWER_ADMIN
    userInfo.account =ENUM_POWER_ADMIN;
    int currentRobotId=1;
    UpdateDataLv1  updateDataLv1;
    p_powerManger->updateControllerInfoLevel1( userInfo, currentRobotId   ,updateDataLv1 );

    QString joyStickConfigFilePath=D_TCRCONTROLLER_DATA_PATH;
    joyStickConfigFilePath+=D_JOYSTICK_CONFIG_FILE_PATH;
    g_joystickDelegate=new JoyStickDelegate(joyStickConfigFilePath);


    
    //程序退出处理

    a.exec();//core dump
//    webobj.closed();
//    webctl.closed();
//    sh.detach();
    robCtl->stop();
    qDebug()<<" baseControl Main thread exit, 程序退出 0！";
    return 0;
}


